/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 11:53:54
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-08-28 00:54:51
 * @FilePath: \keep_motion_api\models\sys\dictData.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const xlsx = require('xlsx'); 
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 字典数据模型
const dictDataSchema = new Schema({
  type_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'DictType',
    required: true 
  },
  label: { type: String, required: true },
  value: { type: String, required: true },
  order: Number,
  status: { type: Boolean, default: true }
});
// 查询字典数据
dictDataSchema.statics.getDictData = async function (code = '', status = '', offset = 0, limit = 10) {
  try {
    const { DictType } = require('./');
    const parentQuery = {};
    if (code) {
      const escapedCode = escapeRegex(code);
      parentQuery.code = { $regex: escapedCode, $options: 'i' };
    }
    const dictTypes = await DictType.find(parentQuery).lean();
    if (dictTypes.length === 0) return { total: 0, rows: [] };

    // 2. 提取所有匹配类型的ID
    const typeIds = dictTypes.map(type => type._id);
    
    const query = {
      type_id: { $in: typeIds },
    };
    if (status) {
      query.status = JSON.parse(status);
    }
    // 先统计符合条件的记录总数
    const total = await this.countDocuments(query);
    // 再进行分页查询
    const rows = await this.aggregate([
      { $match: query },                   // 匹配查询条件
      { $sort: { type_id: 1, order: 1 } },             // 排序
      { $skip: Number(offset) },           // 分页跳过
      { $limit: Number(limit) },           // 分页限制
      // 关联查询（相当于 populate）
      { $lookup: {
          from: 'dicttypes',               // 关联的集合名（通常是模型名小写复数）
          localField: 'type_id',           // 本地关联字段
          foreignField: '_id',             // 关联集合的匹配字段
          as: 'typeInfo'                   // 临时存储关联数据的字段
        }
      },
      { $unwind: '$typeInfo' },            // 展开数组（如果是一对一关系）
      // 投影（展平字段 + 筛选）
      { $project: {
          // 保留原文档字段
          _id: 1, value: 1, label: 1, order: 1, status: 1,
          // 展平关联字段到顶层
          code: '$typeInfo.code',     // 直接映射嵌套字段到顶层
          // 如需保留原type_id可添加: type_id: '$typeInfo._id'
        }
      }
    ]);
    return { rows, total };
  } catch (error) {
    throw error;
  }
}
// 创建字典数据
dictDataSchema.statics.createDictData = async function (code, label, value, order) {
  try {
    const {DictType} = require('./');
    const dictType = await DictType.findOne({ code });
    if(!dictType) throw new Error('字典类型不存在');
    const dictData = new this({
      type_id: dictType._id,
      label,
      value,
      order,
    });
    return dictData.save();
  } catch (error) {
    throw error;
  }
}
// 修改字典数据
dictDataSchema.statics.updateDictData = async function (id, label, value, order) {
  try {
    const dictData = await this.findById(id);
    if(!dictData) throw new Error('字典数据不存在');
    dictData.label = label;
    dictData.value = value;
    dictData.order = order;
    return dictData.save();
  } catch (error) {
    throw error;
  }
}
// 修改字典数据状态
dictDataSchema.statics.updateDictDataStatus = async function (id) {
  try {
    const dictData = await this.findById(id);
    if(!dictData) throw new Error('字典数据不存在');
    dictData.status = !dictData.status;
    return dictData.save();
  } catch (error) {
    throw error;
  }
}
//  excal批量导入
dictDataSchema.statics.importDictData = async function (filePath) {
  try {
    const xlsx = require('xlsx');
    const workbook = xlsx.readFile(filePath);
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    const data = xlsx.utils.sheet_to_json(sheet);
    // 关联字典类型
    const {DictType} = require('./');
    const processedData = [];
    for (const item of data) {
      const dictType = await DictType.findOne({ code: item.code });
      if (!dictType) {
        throw new Error(`字典类型${item.type_id}不存在`);
      }
      processedData.push({
        ...item,
        type_id: dictType._id, // 直接转换为ObjectId
        // 移除Excel中不需要的字段
        __rowNum__: undefined
      });
    }
    // 使用处理后的数据创建文档
    const dictDatas = await this.create(processedData);
    return dictDatas;
  } catch (error) {
    throw error;
  }
}


module.exports = mongoose.model('DictData', dictDataSchema);
